﻿using MyHelper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using HandyControl.Controls;
using System.Windows.Interop;
using System.Diagnostics.Contracts;

namespace weighing
{
    /// <summary>
    /// TestActiveWindow.xaml 的交互逻辑
    /// </summary>
    public partial class TestActiveWindow : GlowWindow
    {
        private bool isGenerating = false;

        public TestActiveWindow()
        {
            InitializeComponent();

            CommonFunction.ShowCustomIcon(this);
        }

        private void GeneraterBtn_Click(object sender, RoutedEventArgs e)
        {
            Generater();
        }

        private void YearsTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (IsNeverCb.IsChecked == false)
                Generater();
        }

        private void Generater()
        {
            if (isGenerating) return;
            isGenerating = true;

            int year = 1;
            if (IsNeverCb.IsChecked == false)
            {
                try
                {
                    year = Convert.ToInt32(this.yearsTb.Text);
                }
                catch (Exception)
                {
                    ConsoleHelper.writeLine(" inoput year is not aviliable value ");
                }
            }
            string code;
            if (this.IsGernalCb.IsChecked == true)
            {
                if (this.SaveFileCb.IsChecked == true)
                {
                    int num = 1;
                    try
                    {
                        num = Convert.ToInt32(this.numsTb.Text);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    bool isNever = (bool)this.IsNeverCb.IsChecked;
                    code = ActiveCodeHelper.GeneraterGernalCode(isNever, year);
                    _ = GenerateAsync(year, isNever, num, code);
                }
                else
                {
                    code = ActiveCodeHelper.GeneraterGernalCode((bool)this.IsNeverCb.IsChecked, year);
                }
            }
            else
            {
                code = ActiveCodeHelper.GeneraterCode((bool)this.IsNeverCb.IsChecked, year);
            }

            this.ActiveCodeTb.Text = code;

            string mw = EncryptHelper.Encrypto(code);
            this.encrytoTb.Text = mw;

            string[] codes = code.Split('-');

            string v = codes[1] + codes[3];
            string mf = EncryptHelper.Encrypto(v) + ".txt";
            this.fileTb.Text = mf;

            string after = EncryptHelper.Encrypto(codes[2] + codes[4]) + ".txt";
            this.afterFileTb.Text = after;
            //生成个文件 
            if (SaveFileCb.IsChecked == true)
            {
                if (IsGernalCb.IsChecked == false)
                {
                    FileHelper.FolderExistsCreater(Constant.ActiveCodePath);
                    FileHelper.CreateFile(Constant.ActiveCodeEncryptFile);
                    FileHelper.Write(Constant.ActiveCodeEncryptFile, mw);
                    //明文
                    FileHelper.CreateFile(Constant.ActiveCodeFile);
                    FileHelper.Write(Constant.ActiveCodeFile, code);
                }
            }
            isGenerating = false;
        }

        public async Task<bool> GenerateAsync(int year = 1, bool isNever = false, int num = 1, string firstCode = null)
        {
            TaskFactory<bool> taskFactory = new TaskFactory<bool>();
            var res = await taskFactory.StartNew(() =>
            {
                StringBuilder sb = new StringBuilder();
                if (num > 1000) num = 1000;
                if (!firstCode.IsNullOrEmpty())
                {
                    num--;
                    sb.AppendLine(firstCode);
                }
                if (num == 0) num = 1;


                for (int i = 0; i < num; i++)
                {
                    sb.AppendLine();
                    var temp = ActiveCodeHelper.GeneraterGernalCode(isNever, year);
                    var enKey = EncryptHelper.Encrypto(temp.Substring(0, 20));
                    sb.AppendLine(temp + " " + enKey);
                }
                //save file
                try
                {
                    var deskPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    var fileName = "GenalCode.txt";
                    var pathFileName = System.IO.Path.Combine(deskPath, fileName);
                    if (FileHelper.Exists(pathFileName))
                    {
                        FileHelper.Write(pathFileName, "");
                    }
                    else
                    {
                        FileHelper.CreateFile(pathFileName);
                    }
                    FileHelper.Write(pathFileName, sb.ToString());
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                return false;
            });
            return res;
        }

        private void IsNeverCb_Changed(object sender, RoutedEventArgs e)
        {

            this.yearsTb.IsEnabled = (bool)!IsNeverCb.IsChecked;

            Generater();
        }

        private void ResolutionBtn_Click(object sender, RoutedEventArgs e)
        {
            string code = this.ActiveCodeTb.Text;
            string vs = "基础版";
            string msg;
            if (code.Length != 29 || !code.StartsWith("BN") || !code.EndsWith("HQ"))
            {
                msg = $"非法的激活码,长度不正确";
                alterInfoTb.Text = msg;
                return;
            }
            string v = code.Substring(2, 1);
            if (v != "B" && v != "H")
            {
                msg = "非法的激活码";
                alterInfoTb.Text = msg;
                return;
            }
            if (v == "H")
            {
                vs = "高级版本";
            }
            string isNerver = code.Substring(8, 1);
            if (isNerver != "T" && isNerver != "F")
            {
                msg = "非法的激活码";
                alterInfoTb.Text = msg;
                return;
            }
            else
            {
                if (isNerver == "T")
                {
                    msg = $"激活码有效,{vs},永久激活";
                }
                else
                {
                    string[] temps = code.Split('-');
                    string y = temps[2].Substring(2, 2) + temps[3].Substring(2, 2) + temps[4].Substring(1, 2);
                    int year = Convert.ToInt32(y) / 365;
                    msg = $"激活码有效,{vs},有效期为 {year} 年";
                }

            }
            msg += ActiveCodeHelper.IsGernalCode(code) ? " 通用 " : "";
            alterInfoTb.Text = msg;
        }

        /// <summary>
        /// 清除 激活码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ClearBtn_Click(object sender, RoutedEventArgs e)
        {
            App.Config.ActiveCode = "";
            App.Config.RadomKey = "";
            App.Config.ActiveTime = null;
            var res = CommonFunction.UpdateAppConfig();
            if (res > 0)
            {
                Console.WriteLine("清除成功");
            }
            else
            {
                Console.WriteLine("清除成功");
            }
        }

    }
}
